package cn.dakaqi.utils.img;

import cn.dakaqi.utils.PropertiesLoader;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;

/**
 * 11  * 将图片转换为Base64<br>
 * 12  * 将base64编码字符串解码成img图片
 * 13  * @创建时间 2015-06-01 15:50
 * 14  *
 * 15
 */
public class Img2Base64Util
{

    private static String addText(String imgFile)throws Exception
    {
        String targetFile = "d:\\pppp.png";
        int x = 120,y = 100;

        File file = new File(imgFile);
        Image src = ImageIO.read(file);
        int width = src.getWidth(null);
        int height = src.getHeight(null);

        // 虚拟图片
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = image.createGraphics();

        // 画目标图片
        g.drawImage(src, 0, 0, width, height, null);

        // 画水印图片
        File file2 = new File("d:\\appicon.png");
        Image markIMG = ImageIO.read(file2);
        int markW = markIMG.getWidth(null);
        int markH = markIMG.getHeight(null);

        //g.drawImage(markIMG, x, y, markW, markH, null);

        //认证情况
        Font f = new Font("Microsoft YaHei",0,14);
        g.setFont (f);
        g.setColor(Color.RED);
        g.drawString("活动编号:1234567890",110,330);
        g.dispose();

        FileOutputStream output = new FileOutputStream(targetFile);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
        encoder.encode(image);
        output.flush();
        output.close();
        return targetFile;
    }

    /**
     * 在二维码上绘制头像
     *
     * @param qr
     * @param portrait
     * @throws java.io.IOException
     */
    private static void createQRCodeBitmapWithPortrait(BufferedImage qr,
                                                       BufferedImage portrait) throws IOException
    {

        // 头像图片的大小
        int tagWidth = 40;
        int tagHeight = 40;

        // 截取成30像素的图片
        BufferedImage tag = new BufferedImage(tagWidth, tagWidth,BufferedImage.TYPE_INT_RGB);

        Graphics tagGrp = tag.getGraphics();
        // 画图形
        tagGrp.drawImage(portrait.getScaledInstance(tagWidth - 1, tagWidth - 1,
                Image.SCALE_SMOOTH), 0, 0, null);
        // 画边框
        tagGrp.setColor(new Color(255, 255, 255));
        tagGrp.drawRect(0, 0, tagWidth - 1, tagHeight - 1);

        int QRCODE_SIZE = qr.getWidth();

        // 设置头像要显示的位置，即居中显示
        int left = (QRCODE_SIZE - tagWidth) / 2;
        int top = (QRCODE_SIZE - tagWidth) / 2;

        Graphics2D g = qr.createGraphics();

        g.drawImage(tag, left, top, null);

    }

    public static void main(String[] args)throws Exception
    {
        PropertiesLoader propertiesLoader = new PropertiesLoader("classpath:resources/utils_parameter.properties");
        System.out.println(propertiesLoader.getProperty("qrpic.path"));
        /*String imgFile = createQRImage("activity","1234567890");//"d:\\123.png";//待处理的图片
        //imgFile = addText(imgFile);
        String imgbese = getImgStr(imgFile);
        System.out.println(imgbese.length());
        System.out.println(imgbese);
        String imgFilePath = "d:\\332.png";//新生成的图片
        generateImage(imgbese, imgFilePath);
        File file = new File(imgFile);
        if(file.exists())
            file.delete();*/
    }

    /**
     * 27      * 将图片转换成Base64编码
     * 28      * @param imgFile 待处理图片
     * 29      * @return
     * 30
     */
    public static String getImgStr(String imgFile)
    {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理


        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try
        {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();

            File file = new File(imgFile);
            if(file.exists())
                file.delete();

        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return new String(Base64.encodeBase64(data));
    }

    /**
     * 53      * 对字节数组字符串进行Base64解码并生成图片
     * 54      * @param imgStr 图片数据
     * 55      * @param imgFilePath 保存图片全路径地址
     * 56      * @return
     * 57
     */
    public static boolean generateImage(String imgStr, String imgFilePath)
    {
        //
        if (imgStr == null) //图像数据为空
            return false;
        try
        {
            //Base64解码
            byte[] b = Base64.decodeBase64(imgStr);
            for (int i = 0; i < b.length; ++i)
            {
                if (b[i] < 0)
                {//调整异常数据
                    b[i] += 256;
                }
            }
            //生成jpeg图片

            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e)
        {
            return false;
        }
    }

    public static String createQRImage(String prefix,String activityCode)
    {
        String path = "";
        try
        {

            //ResourceBundle bundle = ResourceBundle.getBundle("resources/utils_parameter");
            //String savePath = bundle.getString("qrpic.path");
            String savePath = "E:\\lifeyoyo\\dakaqi\\";
            path = savePath + activityCode + "_qr.png"; // 文件物理地址
            File file = new File(path);

            BitMatrix byteMatrix;
            Hashtable hints = new Hashtable();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            byteMatrix = new MultiFormatWriter().encode(prefix+":"+activityCode, BarcodeFormat.QR_CODE, 350, 350, hints);
            MatrixToImageWriter.writeToFile(byteMatrix, "png", file);
        }
        catch (WriterException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();

        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return path;
    }
}
